<template>
  <div class="login">
    <div class="login-box">
      <div class="avatar">
        <img src="./../assets/logo.png" />
      </div>
      <el-form ref="formRef" :model="loginForm" label-width="0px" class="login-form" :rules="rules">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      // 表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入账户名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetForm() {
      this.$refs.formRef.resetFields()
    },
    // 登录
    login() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        this.$http.post('login', this.loginForm).then(({data}) => {
          if(data.meta.status != 200) {
            this.$message.error('登录失败')
          } else {
            this.$message.success('登录成功')
            console.log(data.data.token)
            let token = data.data.token
            window.sessionStorage.setItem('token',token)
            this.$router.push('/home')

          }
        })
      })
    }
  }
}
</script>

<style scoped lang='less'>
.login {
  background: #2b4b6b;
  width: 100%;
  height: 100%;

  .login-box {
    width: 450px;
    height: 300px;
    background: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .avatar {
      height: 130px;
      width: 130px;
      border: 1px solid #eee;
      border-radius: 50%;
      overflow: hidden;
      padding: 10px;
      box-sizing: border-box;
      box-shadow: 0 0 5px #ddd;
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      background: #fff;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background: #eee;
      }
    }

    .login-form {
      width: 100%;
      box-sizing: border-box;
      padding: 0 30px;
      position: absolute;
      bottom: 0;
    }

    .btns {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>